from property import Property
import datetime
from riakmodels.util import pack_date

class DateTimeProperty(Property):
    ''' Used to represent integer values.
    
        DateTimeProperties are stored as strings in the format YYYY-MM-DD HH:MM:SS.MS
        
        Indexed as ``int``. The datetime is packed into an integer.
        
        Keyword Arguments:
            autonow(``bool``): the value will be updated with the current
            timestamp every time the model is saved.
            
            autonowadd(``bool``): the value will be updated with the current
            timestamp the first time the record is created.
    
    '''
    def __init__(self, **kwargs):
        kwargs['type'] = str
        self.autonow = kwargs.pop('autonow', False)
        self.autonowadd = kwargs.pop('autonowadd', False)
        super(DateTimeProperty, self).__init__(**kwargs)
        
    def get_index_types(self):
        return ['int']
        
    def get_index_keys(self):
        return ['%s_int' % self.get_id()]
        
    def encode_index_values(self, v):
        return [pack_date(v)]
        
    def encode_single(self, v):
        if not isinstance(v, datetime.datetime):
            raise ValueError("DateTime property %s value must be a datetime.datetime. Got %s" % (self.get_id(), type(v)))
        return v.strftime("%Y-%m-%d %H:%M:%S.%f")
     
    def encode_other(self, other):
        if isinstance(other, datetime.datetime):
            return pack_date(other)    
        elif isinstance(other, (int, long)):
            return other
        else:
            raise ValueError("Filter value must be a datetime.datetime or int/long. Got %s" % (type(other)))
        
    def decode(self, v):
        return datetime.datetime.strptime(v, "%Y-%m-%d %H:%M:%S.%f")
        
